var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];

function goodsList(data) {

    if(dataSource.length>0){
        dataSource.splice(0, dataSource.length); //清空数组
    }
    if(data.data!=null){
        $.each(data.data.result, function(i, field) {
            var rowData = new Array();
            rowData.push(field.spuCode);
            rowData.push(field.spuImageArr == null ? "" : field.spuImageArr[0]);
            rowData.push(field.name);
            rowData.push(field.subTitile == null ? "" : field.subTitile)
            rowData.push(field.brandName);
            rowData.push(field.skuNumber);
            rowData.push(field.operate);
            rowData.push(field.areaName);
            rowData.push(field.creationDate);
            // rowData.push(field.sendDate);
            rowData.push(field.spuId);
            // rowData.push(field.sale_status);
            var date = new Date(field.creationDate);
            Y = date.getFullYear() + '-';
            M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
            h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
            m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()): date.getMinutes())+ ':';
            s = date.getSeconds()< 10 ? '0'+(date.getSeconds()) : date.getSeconds();

            rowData.push(Y+M+D+h+m+s);

            rowData.push(field.spuId);
            rowData.push(field.saleAreaId);
            rowData.push(field.salesStatus);//14 上下架状态
            dataSource.push(rowData);

        });
    }

    initDataTable(dataSource);

    function initDataTable(dataSource) {
        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "autoWidth": false,
            "ordering": true,
            "searching": true,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [50, 25, 10, 5],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
                "sProcessing": "<img src='./loading.gif' />"
            },
            data: dataSource,
            columnDefs: [{
                "visible": true,
                "targets": 0
            },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span><td><input class="spuId" type="checkbox" name="spuId" value = "' + row[9] + '">' + row[0] + '</td></span>';
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function(data, type, row, meta) {
                        if(row[7] != null&&row[7] !='') {
                            var val = '<span>' + row[7] + '</span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 8
                },

                {
                    "render": function(data, type, row, meta) {
                        var val = '<span></span>';
                        return val;
                    },
                    "targets": 6
                },
                // {
                //     "render": function(data, type, row, meta) {
                //         if(row[8] != null&& row[8] != '') {
                //             var val = '<span>' + row[8] + '</span>';
                //             return val;
                //         }else {
                //             var val = '<span></span>';
                //             return val;
                //         }
                //     },
                //     "targets": 9
                // },
                {
                    "render": function(data, type, row, meta) {
                        if(row[8] != null&&row[8] !='') {
                            var val = '<span>' + row[8] + '</span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 9
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<a class="powerButton 607"><span onclick="goods_check(\'Code列表\',\'goods-sku.html\',' + row[9] + ', ' + row[0] +',\''+row[2]+'\', ' + row[12] +')">查看下级</span></a>';
                        return val;
                    },
                    "targets": 10
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row[1] != '') {
                            var val = '<span id="spuImg1" ><img onclick="picShow(\'查看图片\',\'picShow.html\',\''+row[1]+'\')" src="'+row[1]+'" width="80" height="40"></span>';
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 1
                },
                {
                    "render": function(data, type, row, meta) {
                        if(row[13] != null&&row[13] !='') {
                            if (row[13]==0){
                                var val = '<span>' + '未上架' + '</span>';
                            }else if (row[13]==1){
                                var val = '<span>' + '上架' + '</span>';
                            }else {
                                var val = '<span>' + '下架' + '</span>';
                            }
                            return val;
                        }else {
                            var val = '<span></span>';
                            return val;
                        }
                    },
                    "targets": 7
                },
                {
                    "render": function(data, type, row, meta) {
                        var val = '<span class="shun_text2" style="cursor:pointer;"  title="'+ row[3] +'">'+ row[3] +'</span>';
                        return val;
                    },
                    "targets": 3
                }
            ],
            "fnInitComplete": function(oSettings, json) {
                setBtnDis(0, $("#productManage"));
                $("#datatable").on("change", '.spuId', function() {
                    var num = $(".shun").find("input[type=checkbox]:checked").length;
                    setBtnDis(num, $("#productManage"));
                });
            }
        });
        //权限控制函数
        power()
    };
}

/*表单验证特殊字符*/
function ValidateValue(textbox) {
    var IllegalString = "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘’";
    var textboxvalue = textbox.value;
    var index = textboxvalue.length - 1;
    var s = textbox.value.charAt(index);
    if(IllegalString.indexOf(s) >= 0) {
        s = textboxvalue.substring(0, index);
        textbox.value = s;
        layer.msg("不能输入特殊字符");
    }
}

function goods_listCategory(categoryLevel) {
    console.log($("#class1").val())
    var categoryName = $("#class1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#class1").val(),
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>"
                $("#classUl1").html(classStr);
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#class1").focus(function() {
    $("#classUl1").show();
    goods_listCategory(1);
});
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#classUl1").length == 0 && $(e.target).closest("#class1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#classUl1").hide()
        $("#class2").val();

    }
});
var goodslist_cantegory_id; //定义分类搜索条件

var firstCategoryId;
var secondCategoryId;
var thirdCategoryId;

// 2,3,4级的模糊查询
function getNext_input(level, category_id) {
    if(level == 4) {
        goodslist_cantegory_id = category_id;
        thirdCategoryId = category_id;
    }
    if(level < 4) {
        console.log(level)
        $("#class" + level + "")[0].oninput = function() {
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#class" + level + "").val()
            }
            var succCallBack = function(data, status, response) {
                if(data.errorCode == 0) {
                    if(data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for(var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if(data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#classUl" + nextLevel + "").html(classStr);
                        $("#classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#class" + level + "").focus(function() {
            $("#classUl" + level + "").show();
        });
        $(document).bind("click", function(e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if($(e.target).closest("#classUl" + level + "").length == 0 && $(e.target).closest("#class" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#classUl" + level + "").hide()
            }
        });
    }

}

function nextClass(category_id, level, category_name) {
    $("#class" + level + "").val(category_name);
    if(level == 1) {
        firstCategoryId = category_id;
        $("#class2").val("");
        $("#class3").val("");
    } else if(level == 2) {
        secondCategoryId = category_id;
        $("#class3").val("");
    }
    var user_data = {
        parentCateId: category_id,
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='nextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if(data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#classUl" + nextLevel + "").html(classStr);
                $("#classUl" + nextLevel + "").show();
                $("#classUl" + level + "").hide()
            }
        }
    }
    getNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

/*查看*/
function goods_check(title, url, spuId, spuCode, spuName, saleArea) {
    sessionStorage.removeItem("skuImgCache");
    sessionStorage.setItem("customerId",$("#quyu").val())
    sessionStorage.setItem("areaId",$("#getArea").find("option:selected").val())
    sessionStorage.setItem("spuId", spuId);
    sessionStorage.setItem("spuCode", spuCode);
    sessionStorage.setItem("spuName", spuName);
    console.log("111111")
    if (saleArea == null || saleArea == '' || saleArea == undefined){
        saleArea = -1;
    }
    sessionStorage.setItem("saleArea", saleArea);

    var index = layer.open({
        type: 2,
        title: title,
        content: url
        // content: url + '?priceLockedGoods=' + $(".price-locked-goods").val()
    });
    layer.full(index);
}

/*账户信息编辑*/
function spu_edit(title, url, row) {
    /*删除添加spu图片的缓存，防止刷新页面后缓存不消失*/
    sessionStorage.removeItem("spuImgCache");
    sessionStorage.removeItem("brand_name");
    sessionStorage.removeItem("brand_id");
    sessionStorage.removeItem("attrObjCanch");
    sessionStorage.removeItem("attrId");
    window.session_storage.setItem('spu_id', row)
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

function reloadSpuTable() {
    if ($('#quyu option:selected').val()==0&&$('#getArea option:selected').val()==0){
        layer.msg("请选择渠道商和销售区域");
        return;
    }else{
        if ($('#quyu option:selected').val()==0){
            layer.msg("请选择渠道商");
            return;
        }
        if ($('#getArea option:selected').val()==0){
            layer.msg("请选择销售区域");
            return;
        }
    }


    var customerType = $("input:checkbox[name='customerType']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');

    if(customerType.indexOf("1")>-1 && customerType.indexOf("2")>-1){
        customerType = 3;
    }
    var saleMsg = $("input:checkbox[name='saleArea']:checked").map(function(index,elem) {
        return $(elem).val();
    }).get().join(',');
    if(saleMsg == "" || saleMsg == undefined || saleMsg == null ){
        saleMsg = -1;
    }

    var categoryName = $("#class3").val();
    var firstCategoryName = $("#class1").val();
    var secondCategoryName = $("#class2").val();
    if(categoryName == "" || categoryName == undefined || categoryName == null){
        goodslist_cantegory_id = 0;
        thirdCategoryId= 0;
    }

    if(firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null){
        firstCategoryId = 0;
    }

    if(secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null){
        secondCategoryId = 0;
    }

    $.ajax({
        contentType: 'application/json',
        url: root.dockingplatform.product_manage,
        cache: false, //禁用缓存
        type: "POST",
        data: JSON.stringify({
            rows: 50,
            curPage: 1,
            firstCategoryId : firstCategoryId,
            secondCategoryId :secondCategoryId,
            categoryId: goodslist_cantegory_id,
            spuCode:$("#spu_code").val(),
            skuCode:$("#sku_code").val(),
            helpCode:$("#helpcode").val(),
            name: $("#goodsName").val(),
            brandName: $("#brandName").val(),
            standards:$("#spuStandards").find("option:selected").val(),
            restricted:$("#isLimitCategory").val(),
            startTime:$("#pushDownDateBegin").val(),
            endTime:$("#pushDownDateEnd").val(),
            createStartTime:$("#creationDateBegin").val(),
            createEndTime:$("#creationDateEnd").val(),
            areaId:$("#getArea").find("option:selected").val(),
            customerId:$("#quyu").val(),
            // priceLockedGoods: $(".price-locked-goods").val()
            //传入组装的参数
        }),
        success: function(data) {
            goodsList(data);
            $("#spu_all").attr("checked", false);
            if(data.data!=null){
                totalPage = data.data.totalPage;
            }else{
                totalPage =0
            }
            $('.M-box3').pagination({
                pageCount: totalPage,
                jump: true,
                coping: true,
                prevContent: '上页',
                nextContent: '下页',
                callback: function(api) {
                    console.log(api.getCurrent());
                    $.ajax({
                        contentType: 'application/json',
                        url: root.dockingplatform.product_manage,
                        // url: "http://localhost:8080/product/product/spuList",
                        cache: false, //禁用缓存
                        type: "POST",
                        data: JSON.stringify({
                            rows: 50,
                            curPage: api.getCurrent(),
                            firstCategoryId : firstCategoryId,
                            secondCategoryId :secondCategoryId,
                            categoryId: goodslist_cantegory_id,
                            spuCode:$("#spu_code").val(),
                            skuCode:$("#sku_code").val(),
                            helpCode:$("#helpcode").val(),
                            name: $("#goodsName").val(),
                            brandName: $("#brandName").val(),
                            standards:$("#spuStandards").find("option:selected").val(),
                            restricted:$("#isLimitCategory").val(),
                            startTime:$("#pushDownDateBegin").val(),
                            endTime:$("#pushDownDateEnd").val(),
                            createStartTime:$("#creationDateBegin").val(),
                            createEndTime:$("#creationDateEnd").val(),
                            areaId:$("#getArea").find("option:selected").val(),
                            customerId:$("#quyu").val(),
                        }),
                        success: function(data) {
                            goodsList(data);
                            $("#spu_all").attr("checked", false);
                        }
                    });
                }
            });
        }
    });
}
//获取用户信息
var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
var JsonObject =JSON.parse(localStorageParameters);
//上架
function goods_start(obj, id) {
    console.log(id);
    var spu_data1 = {
        id: id,
    }
    var succCallBack1 = function(data, status, response) {
        if(data.errorCode != 0) {
            $.Huimodalalert(data.errorMessage, 2000);
        }else{
            console.log(id);
            layer.confirm('确认要上架吗？', function(index) {
                var spu_data = {
                    ids: id,
                    status: 1,
                    lastModifiedBy:JsonObject.user.user_ID
                }
                var succCallBack = function(data, status, response) {
                    if(data.errorCode == 0) {
                        layer.msg("上架"+data.data.allSpu+"条spu，失败"+data.data.failSpu+"条，sku失败"+data.data.failSku+"条", {
                            icon: 6,
                            time: 2000
                        }, function() {
                            reloadSpuTable();
                        });
                    }else{
                        layer.msg("上架失败，"+data.errorMessage, {
                            icon: 6,
                            time: 1000
                        }, function() {
                            reloadSpuTable();
                        });
                    }
                };
                return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
            });
        }
    };
    return web.doAjax(root.goodsInter.goods_singleSpuIsPull, 'post', spu_data1, succCallBack1);
}

//下架
function goods_end(obj, id) {
    console.log(id);
    layer.confirm('确认要下架吗？', function(index) {
        var spu_data = {
            ids: id,
            status: 2,
            lastModifiedBy:JsonObject.user.user_ID
        }
        var succCallBack = function(data, status, response) {
            if(data.errorCode == 0) {
                layer.msg("下架成功", {
                    icon: 6,
                    time: 1000
                }, function() {
                    reloadSpuTable();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
    });
}
var allIds = ""; //批量上下架的id
function stopProp() {
    /*批量上架全选框阻止冒泡*/
    var timer = setTimeout(function() {
        var num = $("#datatable").find("tbody").find("input[type=checkbox]:checked").length;
        setBtnDis(num, $("#productManage"));
        clearTimeout(timer);
    }, 200)

    window.event ? window.event.cancelBubble = true : e.stopPropagation();
}

//批量上架
function goods_up(obj) {
    layer.confirm('确认要批量上架吗？', function(index) {
        allIds = document.getElementsByClassName('spuId');
        var ids = [];
        for(var i = 0; i < allIds.length; i++) {
            console.log(allIds[i].checked)
            if(allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for(var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            ids: idStr,
            status: 1,
            lastModifiedBy:JsonObject.user.user_ID
        }
        var succCallBack = function(data, status, response) {
            if(data.errorCode == 0) {
                layer.msg("上架"+data.data.allSpu+"条spu，失败"+data.data.failSpu+"条，sku失败"+data.data.failSku+"条", {
                    icon: 6,
                    time: 2000
                }, function() {
                    reloadSpuTable();
                });
            }else{
                layer.msg("上架失败", {
                    icon: 6,
                    time: 2000
                }, function() {
                    reloadSpuTable();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
    });
}

//批量下架
function goods_down(obj) {
    layer.confirm('确认要批量下架吗？', function(index) {
        allIds = document.getElementsByClassName('spuId');
        var ids = [];
        for(var i = 0; i < allIds.length; i++) {
            console.log(allIds[i].checked)
            if(allIds[i].checked == true) {
                ids.push(allIds[i]);
            }
        }
        var idStr = "";
        for(var i = 0; i < ids.length; i++) {
            idStr += ids[i].value + ","
        }
        idStr = idStr.substring(0, idStr.length - 1);
        var spu_data = {
            ids: idStr,
            status: 2,
            lastModifiedBy:JsonObject.user.user_ID
        }
        var succCallBack = function(data, status, response) {
            if(data.errorCode == 0) {
                layer.msg("批量下架成功", {
                    icon: 6,
                    time: 1000
                }, function() {
                    reloadSpuTable();
                });
            }
        };
        return web.doAjax(root.goodsInter.goods_setSpuSaleStatus, 'post', spu_data, succCallBack);
    });
}

/*商品图片管理-----------------------------------------------------------------------------------*/
function imgGoods_listCategory(categoryLevel) {
    var categoryName = $("#imgClass1").val();
    var user_data = {
        categoryLevel: categoryLevel,
        categoryName: $("#imgClass1").val(),
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>"
                $("#img-classUl1").html(classStr);
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
                $("#img-classUl1").html(classStr);
            }
        }
    }
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}

//获取光标
$("#imgClass1").focus(function() {
    $("#img-classUl1").show();
    imgGoods_listCategory(1);
});
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#img-classUl1").length == 0 && $(e.target).closest("#imgClass1").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $("#img-classUl1").hide()
    }
});
var oneCategoryId = "";
var twoCategoryId = "";
var threeCategoryId = "";
// 2,3,4级的模糊查询
function imgGetNext_input(level, category_id) {
    if(level < 4) {
        $("#imgClass" + level + "")[0].oninput = function() {
            console.log(level)
            console.log($("#imgClass" + level + "").val())
            if(level == 1) {
                oneCategoryId = category_id;
            } else if(level == 2) {
                twoCategoryId = category_id;
            } else if(level == 3) {
                threeCategoryId = category_id;
            }
            var user_data = {
                parentCateId: category_id,
                categoryName: $("#imgClass" + level + "").val()
            }
            var succCallBack = function(data, status, response) {
                console.log(data)
                if(data.errorCode == "0") {
                    if(data.data == null) {
                        classStr = "<li>无数据</li>";
                    } else {
                        var classStr = "";
                        for(var i = 0; i < data.data.length; i++) {
                            classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                        }
                    }
                    if(data.data[0] == undefined) {
                        classValue = category_id;
                        var nextLevel = level + 1;
                        $("#img-classUl" + nextLevel + "").html(classStr);
                        $("#img-classUl" + level + "").hide();
                    } else {
                        var nextLevel = data.data[0].category_level;
                        $("#img-classUl" + nextLevel + "").html(classStr);
                        $("#img-classUl" + level + "").show();
                    }
                }
            }
            web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
        }
        //获取光标
        $("#imgClass" + level + "").focus(function() {
            $("#img-classUl" + level + "").show();
        });
        $(document).bind("click", function(e) {
            //id为menu的是菜单，id为open的是打开菜单的按钮
            if($(e.target).closest("#img-classUl" + level + "").length == 0 && $(e.target).closest("#imgClass" + level + "").length == 0) {
                //点击id为menu之外且id不是不是open，则触发
                $("#img-classUl" + level + "").hide()
            }
        });
    }

}

function imgNextClass(category_id, level, category_name) {
    console.log(level)
    console.log(category_id)
    if(level == 1) {
        $("#imgClass2").val("");
        $("#imgClass3").val("");
    } else if(level == 2) {
        $("#imgClass3").val("");
    }
    if(level == 1) {
        oneCategoryId = category_id;
    } else if(level == 2) {
        twoCategoryId = category_id;
    } else if(level == 3) {
        threeCategoryId = category_id;
    }
    $("#imgClass" + level + "").val(category_name)
    var user_data = {
        parentCateId: category_id
    }
    var succCallBack = function(data, status, response) {
        console.log(data)
        if(data.errorCode == "0") {
            if(data.data == null) {
                classStr = "<li>无数据</li>";
            } else {
                var classStr = "";
                for(var i = 0; i < data.data.length; i++) {
                    classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                }
            }
            if(data.data[0] == undefined) {
                classValue = category_id;
                var nextLevel = level + 1;
                $("#img-classUl" + nextLevel + "").html(classStr);
                $("#img-classUl" + level + "").hide();
            } else {
                var nextLevel = data.data[0].category_level;
                $("#img-classUl" + nextLevel + "").html(classStr);
                $("#img-classUl" + nextLevel + "").show();
                $("#img-classUl" + level + "").hide()
            }
        }
    }
    imgGetNext_input(level + 1, category_id);
    web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
}
var totalPage = 1;

function img_list() {

    var categoryName = $("#imgClass3").val();
    var firstCategoryName = $("#imgClass1").val();
    var secondCategoryName = $("#imgClass2").val();
    if (categoryName == "" || categoryName == undefined || categoryName == null) {
        threeCategoryId = -1;
    }

    if (firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null) {
        oneCategoryId = -1;
    }

    if (secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null) {
        twoCategoryId = -1;
    }

    console.log(JSON.stringify({
        "pageSize": "50",
        "nowPage": 1,
        "model": {
            "spuCode": $("#spuCode").val(),
            "skuCode": $("#skuCode").val(),
            "imgName": $("#imgName").val(),
            "oneCategoryId": oneCategoryId,
            "twoCategoryId": twoCategoryId,
            "threeCategoryId": threeCategoryId
        }
    }))

    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.goodsInter.goods_listImg,
        cache: false, //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "pageSize": "50",
            "nowPage": 1,
            "model": {
                "spuCode": $("#spuCode").val(),
                "skuCode": $("#skuCode").val(),
                "imgName": $("#imgName").val(),
                "oneCategoryId": oneCategoryId,
                "twoCategoryId": twoCategoryId,
                "threeCategoryId": threeCategoryId
            }
        }),
        success: function(data) {
            if(data.errorCode == 0) {
                var imgHtmlStr = "";
                var objList = data.data.list;
                if(objList != null) {
                    for(var i = 0; i < objList.length; i++) {
                        if (objList[i].img_name == null || objList[i].img_name == "null") {
                            objList[i].img_name = "";
                        }
                        if (objList[i].img_url != null && objList[i].img_url != "null") {
                            if (objList[i].use_img == 0) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')" class=" ">修改</a><a class=" " onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                            } else if (objList[i].use_img == 1) {
                                imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                            }
                        }

                    }
                    $("#imgListBox").html(imgHtmlStr);
                }
                totalPage = data.data.totalPage
                $('.M-box4').pagination({
                    pageCount: totalPage,
                    jump: true,
                    coping: true,
                    prevContent: '上页',
                    nextContent: '下页',
                    callback: function(api) {
                        console.log(api.getCurrent());
                        $.ajax({
                            contentType: "application/json",
                            type: "POST",
                            url: root.goodsInter.goods_listImg,
                            cache: false, //禁用缓存
                            dataType: "json",
                            data: JSON.stringify({
                                "pageSize": "50",
                                "nowPage": api.getCurrent(),
                                "model": {
                                    "spuCode": $("#spuCode").val(),
                                    "skuCode": $("#skuCode").val(),
                                    "imgName": $("#imgName").val(),
                                    "oneCategoryId": oneCategoryId,
                                    "twoCategoryId": twoCategoryId,
                                    "threeCategoryId": threeCategoryId
                                }
                            }),
                            success: function(data) {
                                console.log(data);
                                if(data.errorCode == 0) {
                                    var imgHtmlStr = "";
                                    var objList = data.data.list;
                                    if(objList != null) {
                                        for(var i = 0; i < objList.length; i++) {
                                            if (objList[i].img_name == null || objList[i].img_name == "null") {
                                                objList[i].img_name = "";
                                            }
                                            if (objList[i].img_url != null && objList[i].img_url != "null") {
                                                if (objList[i].use_img == 0) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"><a onclick="updataImg(' + objList[i].img_id + ')">修改</a><a onclick="deleteImg(' + objList[i].img_id + ')">删除</a></div></li>';
                                                } else if (objList[i].use_img == 1) {
                                                    imgHtmlStr += '<li><img onclick="picShow(\'查看图片\',\'picShow.html\',\'' + objList[i].img_url + '\',\'500\',\'300\',\'110\')" src="' + objList[i].img_url + '"><div class="num">编码： <span>' + objList[i].img_id + '</span></div><div class="name">名称： <span>' + objList[i].img_name + '</span></div><div class="sale_pic_btn"></div></li>';
                                                }
                                            }

                                        }
                                        $("#imgListBox").html(imgHtmlStr);
                                    }
                                    totalPage = data.data.totalPage
                                }
                            },
                            error: function(XMLHttpRequest, textStatus, errorThrown) {
                                alert(XMLHttpRequest);
                            }
                        });
                    }
                });
                power();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function picShow(title, url, imgUrl) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrl", imgUrl);
    layer_show(title, url, "800", "500");
}

function addImg() {
    layer_show("增加图片", "addPic.html", "600", "500");
}

function updataImg(imgId) {
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.goodsInter.goods_getImg,
        cache: false, //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "imgId": imgId
        }),
        success: function(data) {
            console.log(data);
            if(data.errorCode == 0) {
                // 未使用，随便修
                sessionStorage.setItem("imgInfo", JSON.stringify(data));
                layer_show("修改图片", "can-updataImg.html", "600", "400");

                /*if(data.use_img == 0) {
                } else if(data.use_img == 1) {
                    //已使用，只能修改名字
                    sessionStorage.setItem("imgInfo", JSON.stringify(data));
                    layer_show("修改图片", "cannot-updataImg.html", "600", "400");
                }*/
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function deleteImg(imgId) {
    layer.confirm('确认要删除吗？', function(index) {
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.goodsInter.goods_delImg,
            cache: false, //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "imgId": imgId
            }),
            success: function(data) {
                console.log(data);
                if(data.errorCode == 0) {
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    layer.msg("删除成功", {
                        icon: 6,
                        time: 1000
                    }, function() {
                        img_list();
                    });
                } else {
                    layer.msg(data.errorMessage, {
                        icon: 5,
                        time: 1000
                    }, function() {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    });
}

function setBtnDis(num, pnode) { //如果选中项为空时，置灰相关按钮
    if(num <= 0) {
        pnode.find(".goods_edit").attr("disabled", "disabled").addClass("dis_btn");
    } else {
        pnode.find(".goods_edit").removeAttr("disabled").removeClass("dis_btn");
    }
}
/*对接失败商品导出*/
function exportExcelFn() {
    web.doAjax(root.dockingplatform.rejectSkuCount, 'post', {}, function (data) {
        if(data.errorCode == 0){
            if(data.data==0){
                $.Huimodalalert("无对接失败商品",2000);
            }else {
                window.location.href = root.dockingplatform.exportRejectSkuExcel;
            }
        }else {
            $.Huimodalalert(data.msg,2000);
        }
    },2);
    /*if($("#quyu").val()&&$("#quyu").val()!=0){
        web.doAjax(root.dockingplatform.rejectSkuCount+"/"+$("#quyu").val(), 'post', {}, function (data) {
            if(data.errorCode == 0){
                if(data.data==0){
                    $.Huimodalalert("无对接失败商品",2000);
                }else {
                    window.location.href = root.dockingplatform.exportRejectSkuExcel+"/"+$("#quyu").val()
                }
            }else {
                $.Huimodalalert(data.msg,2000);
            }
        },2);
    }else {
        $.Huimodalalert("请选择渠道商",2000);
    }*/
}
/*成品油转化率维护*/
function oilConversionRate() {
    var content = "oilConversionRate.html";
    var title = "成品油转化率维护"
    var index = layer.open({
        type: 2,
        title: title,
        content: content,
        area: ["100%", "100%"],
    });
}
/*样表下载*/
function downloadExcelTemplateFn() {
    window.location.href = root.dockingplatform.downloadLockPriceProductExcelTemplate;
}
/*管理锁价商品*/
function importPriceLockedGoodsFn() {
    if($("#getArea").val()==0){
        layer.msg("请选择区域", {
            icon: 2,
            time: 3000
        });
        return
    }
    $("#priceLockedGoodsFile").trigger('click');
}
function changeExcelFn(e) {
    var limitSize = 5*1024*1024;
    var fileDir = $("#priceLockedGoodsFile").val();
    var suffix = fileDir.substr(fileDir.lastIndexOf("."));
    var file = $("#priceLockedGoodsFile")[0].files[0];
    if ("" == fileDir) {
        layer.msg("请选择excel文件", {
            icon: 2,
            time: 3000
        });
        return;
    }
    if (".xls" != suffix && ".xlsx" != suffix) {
        layer.msg("格式错误", {
            icon: 2,
            time: 3000
        });
        $('#priceLockedGoodsFile').val("");
        return;
    }
    if(file.size>limitSize){
        $.Huimodalalert('请上传5M以内的excel文件',2000);
        return;
    }
    var formData = new FormData();
    formData.append("file", $("#priceLockedGoodsFile")[0].files[0]);
    formData.append("operateUserName", JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name);
    formData.append("areaId", $("#getArea").val());
    $.ajax({
        url: root.dockingplatform.excelImportLockPriceProduct,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        data: formData,
        success: function (data) {
            console.log(data)
            if (data.errorCode == 0) {
                layer.msg("excel上传成功!", {icon: 6, time: 3000});
                var fileUpEl = document.getElementById('priceLockedGoodsFile') ;
                fileUpEl.outerHTML=fileUpEl.outerHTML;
            } else {
                layer.alert(data.msg, {icon: 2});
                var fileUpEl = document.getElementById('priceLockedGoodsFile') ;
                fileUpEl.outerHTML=fileUpEl.outerHTML;
            }
        }
    });
}
/*导出锁价商品*/
function exportPriceLockedGoodsFn() {
    if($("#quyu").val() == '' || $("#quyu").val() == 0) {
        layer.msg("请选择渠道", {
            icon: 2,
            time: 3000
        });
        return
    }
    window.open(root.dockingplatform.exportLockPriceProductPriceExcel + '?customerId=' + $("#quyu").val());
}



//渠道商模糊查询
function findAllInfo (name) {
    var params = {
        status: '',
        name: name
    }
    var successData = function (data) {
        if (data.code == 0) {
            if (data.data && data.data.length > 0) {
                var result = data.data;
                var str = ''
                result.forEach(function (item) {
                    str += '<li class="search-item" data-id="' + item.id + '">' + item.name + '</li>'
                });
                $('.search').html(str)
            } else {
                var emptyStr = '<li class="search-item">暂无数据</li>';
                $('.search').html(emptyStr)
            }
        }
    }
    return web.doAjax(root.serviceProviderManagement.findAll, 'post', params, successData, 2);
}

// 服务商模糊搜索
$('#providerId').on('keyup', function () {
    $('.search').show();
    approvalProduct.findAllInfo($('#providerId').val())
});

// 选择服务商查询结果
$('.search').delegate('.search-item', 'click', function () {
    var itemId = $(this).attr('data-id');
    var itemName = $(this).text();
    $('.service-productName').val(itemName);
    $('.search').hide();
    approvalProduct.params.providerId = itemId;
});